'''
matplotlib script called by gather.py
takes path to data file, output dir,
and go source dir as arguments.
'''

import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

def read_args():
  repopath = sys.argv[1]
  outdir = sys.argv[2]
  # Display stats of gosrc as reference
  try:
    refdir = sys.argv[3]
  except:
    refdir = None
  return repopath, outdir, refdir

def read_data(repopath, refdir):
  # Read in the data values from file
  rep = np.fromfile(repopath, sep='\n')
  reffile = refdir + '/' + repopath.split('/')[-1] 
  if refdir != None and os.path.exists(reffile):
    ref = np.fromfile(reffile, sep='\n')
  else:
    ref = np.array([0])
  return rep, ref

def plot_hist(metric, data, subplot, color):
  l, h = min(data), max(data)
  # Width of the bars, max # bins = 100
  if h-l > 1:
    d = int((h-l)/100)
    d = max(d, 1)
  else:
    d = float((h-l)/10)
  # Compute mean, stddev, and max
  # Only show up to 2 digits after decimal place
  mu = np.round(np.mean(data)*100)/100.0
  sigma = np.round(np.std(data)*100)/100.0
  mx = np.round(np.max(data)*100)/100.0
  # Begin plot
  plt.subplot(subplot)
  # Experimenting with when to use log scale, both x and y-axis
  plt.hist(data, bins=np.arange(l, h+2, d), color=color, alpha=0.75, align='left', normed=False)#, log=(mx > 100*mu))
  plt.xlabel(metric)
  if (h-l > 1000):
    plt.xscale('log')
  else:
    plt.xscale('linear')
  # For ticks to be in middle of bars
  shift = 1 if (mx > 100) else 0.5
  plt.xlim(l-shift, h+0.5)
  plt.ylabel('File count')
  plt.title(r'$\mu='+str(mu)+',\ \sigma='+str(sigma)+',\ max='+str(mx)+'$')

# Run
repopath, outdir, refdir = read_args()
# Get the metric name from the input filename
# TODO: Find cleaner way to do this
metric = repopath.split('/')[-1].split('.')[0].replace('_', ' ')
rep, ref = read_data(repopath, refdir)
# First plot
plot_hist(metric, rep, 211, 'lightblue')
plt.subplots_adjust(hspace=0.4)
# Second plot
plot_hist(metric, ref, 212, 'orange')
# Save figure
plt.savefig(os.path.join(outdir, metric.replace(' ', '_') + '.png'))
